package comnet.daytime;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, Nov 14, 2007
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DayTimeClient {
    private String host;
    private int port;
    private DatagramSocket socket = null;
    private byte[] buffer;
    private DatagramPacket packet;
    private InetAddress serverAddress;

    public DayTimeClient(String host, int port) {
        this.host = host;
        this.port = port;
        buffer = new byte[512];
    }

    public static void main(final String[] args) {
        if (args.length < 1) {
            System.out.println("usage: DayTimeClient <IPaddress> [port]");
            System.exit(0);
        }

        String h = args[0];

        int p = 0;
        if (args.length == 2) {
            try {
                p = Integer.parseInt(args[1]);

                if (p < 0 || p > 65535) {
                    System.out.println("Error in port number. Valid values: 0 - 65535");
                    return;
                }
            } catch (NumberFormatException e) {
                p = 13;
            }
        }

        new DayTimeClient(h, p).runClient();
    }

    public void runClient() {
        try {
            packet = new DatagramPacket(buffer, buffer.length);
            serverAddress = InetAddress.getByName(host);
            socket = new DatagramSocket();

            packet.setAddress(serverAddress);
            packet.setPort(port);
            socket.send(packet);
            socket.receive(packet);

            System.out.println(new String(packet.getData()).trim());
        } catch (IOException ie) {
            System.out.println(ie.toString());
            System.exit(1);
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
}